from django.shortcuts import get_object_or_404
from django.contrib.admin.views.decorators import staff_member_required
from django.utils.functional import curry
from django.utils.translation import ugettext as _
from django.http import HttpResponseRedirect
from django.db import models

def redirect(request, instance=None):
	if 'HTTP_REFERER' in request.META:
		return HttpResponseRedirect(request.META['HTTP_REFERER'])
	else:
		return HttpResponseRedirect('/admin/') # FIXME: set a valid url

def move(user, instance, query_suffix, direction_verbose_name):
	model = instance.__class__
	try:
		swap_instance = model.objects.filter(**{'admin_ordering__'+query_suffix: instance.admin_ordering}).order_by('-admin_ordering')[0]
	except IndexError:
		# No model to swap with
		user.message_set.create(message=_('Nothing changed'))
		return
	
	instance.admin_ordering, swap_instance.admin_ordering = swap_instance.admin_ordering, instance.admin_ordering
	
	instance.save()
	swap_instance.save()
	
	user.message_set.create(message=_('"%(instance)s" moved %(direction)s') % \
		{'instance': instance, 'direction': _(direction_verbose_name)})

ACTIONS = {
	'up': curry(move, query_suffix='lt', direction_verbose_name='up'),
	'down': curry(move, query_suffix='gt', direction_verbose_name='down'),
}

@staff_member_required
def order(request, app_label, model_name, pk):
	direction = request.GET.get('direction')
	
	if direction not in ACTIONS.keys():
		return redirect(request)
	
	model = models.get_model(app_label, model_name)
	if model is None:
		return redirect(request)
	
	opts = model._meta
	
	if not opts.orderable or \
	  not request.user.has_perm(opts.app_label + '.' + opts.get_change_permission()):
		return redirect(request)
	
	instance = get_object_or_404(model, pk=pk)
	
	ACTIONS[direction](request.user, instance)
	
	return redirect(request, instance)